"""
日志管理模块
基于loguru实现的多级日志系统
"""

import sys
import os
from pathlib import Path
from loguru import logger
from typing import Optional
from .config import config


class LoggerManager:
    """日志管理器"""
    
    def __init__(self):
        self._setup_logger()
    
    def _setup_logger(self):
        """设置日志配置"""
        # 移除默认的控制台处理器
        logger.remove()
        
        # 确保日志目录存在
        log_dir = Path(config.directories.logs)
        log_dir.mkdir(parents=True, exist_ok=True)
        
        # 控制台日志格式
        console_format = (
            "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
            "<level>{level: <8}</level> | "
            "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
            "<level>{message}</level>"
        )
        
        # 文件日志格式
        file_format = (
            "{time:YYYY-MM-DD HH:mm:ss} | "
            "{level: <8} | "
            "{name}:{function}:{line} | "
            "{message}"
        )
        
        # 添加控制台处理器
        logger.add(
            sys.stdout,
            format=console_format,
            level=config.system.log_level,
            colorize=True,
            backtrace=True,
            diagnose=True
        )
        
        # 添加文件处理器 - 所有日志
        logger.add(
            log_dir / "app.log",
            format=file_format,
            level="DEBUG",
            rotation="100 MB",
            retention="30 days",
            compression="zip",
            encoding="utf-8",
            backtrace=True,
            diagnose=True
        )
        
        # 添加错误日志文件处理器
        logger.add(
            log_dir / "error.log",
            format=file_format,
            level="ERROR",
            rotation="50 MB",
            retention="90 days",
            compression="zip",
            encoding="utf-8",
            backtrace=True,
            diagnose=True
        )
        
        # 添加性能日志文件处理器
        if config.monitoring.performance_logging:
            logger.add(
                log_dir / "performance.log",
                format=file_format,
                level="INFO",
                rotation="50 MB",
                retention="7 days",
                compression="zip",
                encoding="utf-8",
                filter=lambda record: "PERFORMANCE" in record["message"]
            )
    
    def get_logger(self, name: Optional[str] = None):
        """获取日志器实例"""
        if name:
            return logger.bind(name=name)
        return logger
    
    def set_level(self, level: str):
        """动态设置日志级别"""
        # 这里需要重新配置logger，loguru不支持动态修改级别
        # 可以通过重新初始化来实现
        pass


# 全局日志管理器实例
log_manager = LoggerManager()

# 导出常用的日志器
app_logger = log_manager.get_logger("app")
video_logger = log_manager.get_logger("video")
detection_logger = log_manager.get_logger("detection")
ocr_logger = log_manager.get_logger("ocr")
queue_logger = log_manager.get_logger("queue")
storage_logger = log_manager.get_logger("storage")
api_logger = log_manager.get_logger("api")
performance_logger = log_manager.get_logger("performance")
